﻿/*****************************************************************************
Copyright (c) 2011 SmartVault, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
******************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using SmartVault.Proto;
using SmartVault.Net.Http;
using Google.ProtocolBuffers;

namespace SmartVault.Net
{
    /// <summary>
    /// MimeSectionWriter
    /// 
    /// Used to write a mime section in a multipart mime message.
    /// </summary>
    public class MultipartMimeWriter
    {
        private Stream Stream { get; set; }
        private byte[] Boundary { get; set; }
        private byte[] MimeBoundaryStartBinary { get; set; }
        private byte[] CRLFBinary { get; set; }

        public MultipartMimeWriter(Stream s)
            : this (s, Guid.NewGuid().ToByteArray())
        {

        }

        private MultipartMimeWriter(Stream s, byte[] boundary)
        {
            this.Stream = s;

            // length of 1 .. 71
            if (boundary.Length < 1 || boundary.Length > 71)
            {
                throw new ArgumentException();
            }

            // Boundary must be 7bit encoded
            for (int i = 0; i < boundary.Length; ++i)
            {
                if (boundary[i] > byte.MaxValue)
                {
                    throw new ArgumentException();
                }
            }

            this.Boundary = boundary;
            this.MimeBoundaryStartBinary = Constants.MimeBoundaryStartBinary;
            this.CRLFBinary = Constants.CRLFBinary;
        }

        private void WriteHeader(string name, string value)
        {
            string tmp = String.Format("{0}: {1}{2}", name, value, Constants.CRLF);
            byte[] header = Encoding.ASCII.GetBytes(tmp);
            this.Stream.Write(header, 0, header.Length);
        }

        private void WriteContentType(MediaType contentType)
        {
            WriteHeader(Constants.ContentType, contentType.ToString());
        }

        private void WriteBoundary(bool last)
        {
            // write boundary
            this.Stream.Write(this.MimeBoundaryStartBinary, 0, this.MimeBoundaryStartBinary.Length);
            this.Stream.Write(this.Boundary, 0, this.Boundary.Length);
            if (last)
            {
                this.Stream.Write(this.MimeBoundaryStartBinary, 0, this.MimeBoundaryStartBinary.Length);
            }
            this.Stream.Write(this.CRLFBinary, 0, this.CRLFBinary.Length);
        }

        public void Write(IMessage envelope, MediaType contentType)
        {
            // boundary
            WriteBoundary(false);      
   
            // content type
            WriteContentType(contentType);

            // end header
            this.Stream.Write(this.CRLFBinary, 0, this.CRLFBinary.Length);

            ProtoSerializerNet ser = new ProtoSerializerNet();
            ser.MimeTypes = contentType.Type;
            ser.Encoding = Encoding.ASCII;      // not sure if this is correct. MRW 06-04-2011
            ser.Write(this.Stream, envelope);

            // carriage return
            this.Stream.Write(this.CRLFBinary, 0, this.CRLFBinary.Length);
        }

        public void Write(Stream stream)
        {
            // boundary
            WriteBoundary(false);  

            /*
            // write content type
            WriteContentType(rdr.Descriptor.Type);

            // add length
            WriteHeader(Constants.ContentLength, rdr.Descriptor.Length.ToString());
            */

            // end header
            this.Stream.Write(this.CRLFBinary, 0, this.CRLFBinary.Length);

            // write body
            byte[] buffer = new byte[short.MaxValue];
            int len;
            while (0 != (len = stream.Read(buffer, 0, buffer.Length)))
                this.Stream.Write(buffer, 0, len);

            // carriage return
            this.Stream.Write(this.CRLFBinary, 0, this.CRLFBinary.Length);
        }

        public void Complete()
        {
            WriteBoundary(true);
        }
    }
}
